package com.ymk.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ymk.base.cmd.CmdSign;
import com.ymk.base.exception.MallException;
import com.ymk.base.utlis.ParamsBuilder;
import com.ymk.bo.mch.MchBO;
import com.ymk.bo.pay.PayPaymentBO;
import com.ymk.core.constants.PayConstants;
import com.ymk.core.constants.SysConstants;
import com.ymk.core.constants.WxConstants;
import com.ymk.core.enums.pay.PayStatusEnum;
import com.ymk.service.WxService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

@Service
public class WxServiceImpl implements WxService {

    private final static Logger logger = LoggerFactory.getLogger(WxServiceImpl.class);

    @Override
    public PayPaymentBO wxPay(CmdSign sign, MchBO mchBO, PayPaymentBO payPaymentBO) throws Exception {
        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("service","dev-ymk-order")
                .addParam("path","/wxPay/payNotify");
        ParamsBuilder params = ParamsBuilder.newBuild()
                .addParam("body", mchBO.getTitle() + "统一下单")
                .addParam("openid", sign.getToken())
                .addParam("out_trade_no", payPaymentBO.getPayNo())
                .addParam("spbill_create_ip", sign.getIp())
                .addParam("env_id", WxConstants.X_WX_ENV)
                .addParam("sub_mch_id", mchBO.getWxMchId())
                .addParam("total_fee", payPaymentBO.getAmount().multiply(new BigDecimal("100")))
                .addParam("callback_type", 2)
                .addParam("container", paramsBuilder.build());
        logger.info(JSON.toJSONString(params.build()));
        String resData = HttpUtil.post(WxConstants.WX_PAY_URL, JSON.toJSONString(params.build()));
        if(StringUtils.isBlank(resData)){
            logger.error(resData);
            throw new MallException("支付异常");
        }
        logger.info(resData);
        JSONObject param = JSON.parseObject(resData);
        if (WxConstants.RESPONSE_SUCCESS.equals(param.getString("errmsg"))){

            payPaymentBO.setReqData(param.getString("respdata"));

            return payPaymentBO;
        }else {
            logger.error(resData);
            throw new MallException("支付异常");
        }
    }

    @Override
    public PayPaymentBO syncWxPay(PayPaymentBO payPaymentBO,MchBO mchBO) throws Exception {

        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("out_trade_no", payPaymentBO.getPayNo())
                .addParam("sub_mch_id", mchBO.getMchUserId());

        String resData = HttpUtil.post(WxConstants.QUERY_WX_PAY_URL, JSON.toJSONString(paramsBuilder.build()));

        JSONObject paramObject = JSON.parseObject(resData);
        //处理成功
        if (WxConstants.RESPONSE_SUCCESS.equals(paramObject.getString("errmsg"))) {

            JSONObject param = paramObject.getJSONObject("respdata");
            if (param.getString("return_code").equals("SUCCESS")){

                payPaymentBO.setStatus(PayStatusEnum.ACCOUNT_PAID.getStatus());
                payPaymentBO.setTradeNo(param.getString("transaction_id"));
                payPaymentBO.setPayDate(new Date());
                BigDecimal totalAmount = new BigDecimal(param.getString("total_fee"));
                payPaymentBO.setAmount(totalAmount.divide(new BigDecimal("100"),BigDecimal.ROUND_CEILING));
                return payPaymentBO;
            }
        } else {
            logger.error(resData);
            payPaymentBO.setStatus(PayStatusEnum.EXCEPTION.getStatus());
            payPaymentBO.setSyncData(resData);
        }
        return payPaymentBO;
    }
}
